package com.houdoudou.customer.buy;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.customer.R;
import com.houdoudou.customer.buy.OrderDetailFrg.ProductListAdapter.Zujian;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.DateTimeFunction;
import com.houdoudou.customer.common.ListViewUtil;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo.DetailedState;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class OrderStateFrg  extends Fragment{

	TextView orderID, orderStateWord;
	ListView stateListView;
	JSONArray statesJA= new JSONArray();
	Button function1,function2,function3;
	private String TIME="time";
	private String AFFAIR="affair";
	private String NOTE="note";
	private String AFFAIR_PROTECTORDER="protectOrder";
	private String AFFAIR_CANCELORDER="cancelOrder";
	StateListAdapter stateListAdapter;
	View.OnClickListener myClickListener;
	int orderState=OrderDetailAct.orderJO.getInt(Order.STATE);
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.frg_orderstate, container, false);
		init_listener();
		orderID= (TextView) view.findViewById(R.id.tv_orderid_frgorderstate);
		orderStateWord= (TextView) view.findViewById(R.id.tv_state_frgorderstate);
		stateListView= (ListView) view.findViewById(R.id.listview_frgorderstate);
	//	orderSecret= (TextView) view.findViewById(R.id.tv_secret_frgorderstate);
		function1= (Button) view.findViewById(R.id.btn_function1_frgorderstate);
		function2= (Button) view.findViewById(R.id.btn_function2_frgorderstate);
		function3= (Button) view.findViewById(R.id.btn_function3_frgorderstate);
		function1.setOnClickListener(myClickListener);
		function2.setOnClickListener(myClickListener);
		function3.setOnClickListener(myClickListener);
		stateListAdapter=new StateListAdapter(getActivity());
		stateListView.setAdapter(stateListAdapter);
		
		 IntentFilter filter = new IntentFilter(ChoosePayAct.ACTION_ORDER_CHANGED);  
	        getActivity().registerReceiver(broadcastReceiver, filter);  
	        
		return view;		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		assign_component();
	}
	 BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  
			
	       @Override  
	       public void onReceive(Context context, Intent intent) {  
          // TODO Auto-generated method stub  
	    	   String orderJOStr= intent.getExtras().getString("order");
	    	   OrderDetailAct.orderJO= JSONObject.fromObject(orderJOStr);	
	    	   System.out.println("OrderStatefrg broadcastReceiver order id="+OrderDetailAct.orderJO.getLong(Order.ID));
	    	   assign_component();
	       }  
	   };  
	private void assign_component(){
		System.out.println(" assign_component(); id doing ");
		orderID.setText("订单号："+OrderDetailAct.orderJO.getLong(Order.ID));
		int state=OrderDetailAct.orderJO.getInt(Order.STATE);
		orderStateWord.setText("状态："+CommonFunction.spellOrderStateWord(state));
		//二维码何时显示
		if(orderState==21){
		function2.setVisibility(View.VISIBLE); 
		}else{
			function2.setVisibility(View.GONE); 
		}//取消订单何时显示
		if(orderState==1){ 	
			function3.setVisibility(View.VISIBLE); 
			}else{		
				function3.setVisibility(View.GONE); 	
			}	
		// 付款何时显示  未支付&&订单状态&&不超时
		boolean isPayShow=(orderState==1||orderState==2)&&OrderDetailAct.orderJO.getInt(Order.ISMONEYPAID)==1;
		long dateTimeAA=Long.parseLong(OrderDetailAct.orderJO.getString(Order.DATETIMEAA));
		isPayShow= isPayShow&&(DateTimeFunction.myDateTimeValue(new Date())<dateTimeAA);
		if(isPayShow){
			function1.setVisibility(View.VISIBLE); 
		}else{
			function1.setVisibility(View.GONE); 
		}
		
		figureOutState();
		System.out.println("statesJA.size()"+statesJA.size());
		stateListAdapter.notifyDataSetChanged();
		ListViewUtil.setListViewHeightBasedOnChildren(stateListView);
	}
	private void init_listener(){
		myClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(v==function1){
				                      //立即付款
						String[] params= new String[3];
				         params[0]=Constant.BaseUrl+Constant.CustomerUrl;
				         params[1]=AFFAIR_PROTECTORDER; //PostCod
				         JSONObject jsonData=new JSONObject();
				         jsonData.put("customer", Constant.customerJO);
				         JSONObject orderTempJO= new JSONObject();
				         orderTempJO.put(Order.ID,OrderDetailAct.orderJO.getLong(Order.ID));
				         jsonData.put("order", orderTempJO);
				        params[2]=jsonData.toString();
				      new HttpPostTaskforOrderDo().execute(params);
				
				}
				if(v==function2){
					if(orderState==1){ //二维码取件
						
					}
				}
				if(v==function3){//取消订单
					String[] params= new String[3];
			         params[0]=Constant.BaseUrl+Constant.CustomerUrl;
			         params[1]=AFFAIR_CANCELORDER; //PostCod
			         JSONObject jsonData=new JSONObject();
			         jsonData.put("customer", Constant.customerJO);
			         JSONObject orderTempJO= new JSONObject();
			         orderTempJO.put(Order.ID,OrderDetailAct.orderJO.getLong(Order.ID));
			         jsonData.put("order", orderTempJO);
			        params[2]=jsonData.toString();
			      new HttpPostTaskforOrderDo().execute(params);
					
				}
			}
		};
	}
	
	private void figureOutState(){
		
		statesJA.clear();
		
		 JSONObject stateJO= new JSONObject();stateJO.put(NOTE, "");
		if(orderState>=1){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMEPL)); 
			stateJO.put(AFFAIR, "下单");  statesJA.add(stateJO); }	
		if(orderState==3){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMERF)); 
			stateJO.put(AFFAIR, "取消订单");  stateJO.put(NOTE, "过时未支付，自动取消");
			statesJA.add(stateJO);
			return; }
		if(orderState==4){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMERF)); 
			stateJO.put(AFFAIR, "取消订单");  stateJO.put(NOTE, "主动取消订单");
			statesJA.add(stateJO); 
			return;}
	
		//orderState==10，意味着，已支付要送货的订单。
		
		if(OrderDetailAct.orderJO.getInt(Order.ISMONEYPAID)==2){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMEPA)); 
			stateJO.put(AFFAIR, "支付");   statesJA.add(stateJO); }
		
		if(orderState==5){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMERF)); 
			stateJO.put(AFFAIR, "取消订单");  stateJO.put(NOTE, "商家取消订单");
			statesJA.add(stateJO); 
		
			 return; }	
		
		if(orderState>=21){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMEAI)); 
			stateJO.put(AFFAIR, "送达");  stateJO.put(NOTE, "送货员："+OrderDetailAct.orderJO.getString(Order.COURIERAITELNUM));
			statesJA.add(stateJO); 
			}
		if(orderState==22){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMETK)); 
			stateJO.put(AFFAIR, "收货"); stateJO.put(NOTE,"消费者取走订单");
			statesJA.add(stateJO); }
		if(orderState==23){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMERK)); 
			stateJO.put(AFFAIR, "取回"); stateJO.put(NOTE,"客户过时未取，商家取回，"+"送货员："+OrderDetailAct.orderJO.getString(Order.COURIERRKTELNUM));
			statesJA.add(stateJO); }
		if(orderState==24){
			stateJO.put(TIME, OrderDetailAct.orderJO.getString(Order.DATETIMERK)); 
			stateJO.put(AFFAIR, "抛弃"); stateJO.put(NOTE,"客户过时未取，商家过时未取回，订单被抛弃，送货员："+OrderDetailAct.orderJO.getString(Order.COURIERABTELNUM));
			statesJA.add(stateJO); }
		
	}
	
	
class StateListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    private int parentPosition;
	        public StateListAdapter(Context context) {
				
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		  
		}


	    final class Zujian{  
	         public TextView time,affair; 
	       
	      
	        }  
	          @Override
	       public int getCount() {
		// TODO Auto-generated method stub
		    return statesJA.size();  
	        	 
	       }

	      @Override
	       public Object getItem(int position) {
		// TODO Auto-generated method stub
		       return statesJA.getJSONObject(position);  
	    	 
	          }

	    @Override
	     public long getItemId(int position) {
		// TODO Auto-generated method stub
		       return position; 
	       }

	               @Override
	    public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int childID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_orderstate, null);              
	            zj.time=(TextView) convertView.findViewById(R.id.tv_time_list_frgorderstate);
	            zj.affair=(TextView) convertView.findViewById(R.id.tv_affair_list_frgorderstate);
	            convertView.setTag(zj);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据  
	        zj.time.setText(statesJA.getJSONObject(childID).getString(TIME));
	        zj.affair.setText(statesJA.getJSONObject(childID).getString(AFFAIR));
	       
	        
	   //     imageLoader.showImageAsyn(zj.img, record.getString(Product.DIR), R.drawable.p3);       
	        return convertView;
	       } 
	         }// end Adapter

	
	

private  class HttpPostTaskforOrderDo extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
				
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(getActivity(), "温馨提示", "无网络连接");return;
		      
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				String affair="";
				JSONObject json = null;
				 JSONObject orderJOOnline;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				 affair= json.getString("affair");
				
				}catch(JSONException e){
					 CommonFunction.alert(getActivity(), "温馨提示", "很抱歉，回传数据解析错误。");return;
				}
				 if(!success){  CommonFunction.alert(getActivity(), "温馨提示", "很抱歉,"+errorInfo);return;}
				 
				if(affair.equals(AFFAIR_PROTECTORDER)){						   												      		       
		               orderJOOnline= json.getJSONObject("order");  
		              if(orderJOOnline.getInt(Order.STATE)!=2){
		            	  OrderDetailAct.orderJO.put(Order.STATE, orderJOOnline.getInt(Order.STATE));
		            	  OrderDetailAct.orderJO.put(Order.DATETIMERF, orderJOOnline.getInt(Order.DATETIMERF));
		             assign_component(); 
		        	 CommonFunction.alert(getActivity(), "温馨提示", "很抱歉，"+errorInfo+"无法完成支付。");return; 
		        	 }else{
		         Intent intent = new Intent(getActivity(), ChoosePayAct.class);
	              intent.putExtra("order", OrderDetailAct.orderJO.toString());
               	startActivity(intent);  }	         
				}
				if(affair.equals(AFFAIR_CANCELORDER)){
					 orderJOOnline= json.getJSONObject("order");
					  Intent intent = new Intent(ChoosePayAct.ACTION_ORDER_CHANGED);  
					   intent.putExtra("order", orderJOOnline.toString());  
					   getActivity().sendBroadcast(intent); 
					   CommonFunction.alert(getActivity(), "成功","取消订单成功");
					   try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
					   assign_component();
				}
				
		  		// OrderDetailAct.this.finish();
			
		} //onPostExecute
	} //AsyncTask
	
}
